package com.lemon.kenhnhacvn;

import java.util.ArrayList;

import org.json.JSONException;

import saucaca.JSON.JsonReader;
import saucaca.JSON.WServiceLib;
import saucaca.Object.HomeData;
import saucaca.Object.SongObject;
import saucaca.Util.CMD;
import saucaca.Util.CirclePageIndicator;
import saucaca.Util.PageIndicator;
import saucaca.Util.PreferenceUtils;
import saucaca.Util.TagName;
import saucaca.Video.FullScreenVideoStreamView;
import saucaca.Video.VideoControllerStreamView;
import saucaca.fragment.CommentFragment;
import saucaca.fragment.VideoDetaisFragment;
import saucaca.fragment.YoutubeFragment;
import android.annotation.SuppressLint;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

@SuppressLint("DefaultLocale")
public class VideoPlayActivity extends FragmentActivity implements FullScreenVideoStreamView.ToggleFullScreen {
	public String YOUTUBE = "1";
	public String LINK = "2";
	// private final String VIDEO_STREAM =
	// "http://www.pocketjourney.com/downloads/pj/video/famous.3gp";
	private FullScreenVideoStreamView mVideoView;
	private ProgressBar bar;
	int height;
	int width;
	RelativeLayout relativeLayout;
	public static SongObject songObject;
	public static ArrayList<SongObject> listSongs;
	boolean isOnline = false;

	ViewPager viewPager;
	PageIndicator mIndicator;
	public OfflineTabPageAdapter TabAdapter;
	int index=-1;
	YoutubeFragment menuFragment;
	boolean isYoutubeAPI=false;
	@SuppressWarnings("unchecked")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.video_stream);
		relativeLayout = (RelativeLayout) findViewById(R.id.video_realati_videoview);
		DisplayMetrics metrics = getResources().getDisplayMetrics();
		int h=0;
		if (metrics.widthPixels < metrics.heightPixels) {
			h = (int) (metrics.widthPixels / 1.66);
		}
		LinearLayout.LayoutParams layoutParams = (android.widget.LinearLayout.LayoutParams) relativeLayout.getLayoutParams();
		layoutParams.height = h;
		relativeLayout.setLayoutParams(layoutParams);
		relativeLayout.requestLayout();
		
		Bundle extras = getIntent().getExtras();
		if(getIntent().hasExtra(MainActivity.INDEX))
			index=extras.getInt(MainActivity.INDEX);
		if(index>=0){
			listSongs=(ArrayList<SongObject>)extras.getSerializable(MainActivity.ID);
			songObject=listSongs.get(index);
		}else{
			songObject = (SongObject) extras.getSerializable(MainActivity.ID);
		}
//		songObject.showSonginfo();
		
		bar = (ProgressBar) findViewById(R.id.videoplayerPreloader);
		mVideoView = (FullScreenVideoStreamView) findViewById(R.id.video_view);
		viewPager = (ViewPager) findViewById(R.id.viewpagerVideo);
		mIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
		setVideo();
	}

	public void playYoutubeAPI(String videoID){
		mVideoView.setVisibility(View.GONE);
		bar.setVisibility(View.GONE);
		isYoutubeAPI=true;
		mVideoView.setDimensions(0, 0);
		menuFragment = YoutubeFragment.newInstance(videoID);
		FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
		fragmentTransaction.replace(R.id.video_container, menuFragment, menuFragment.getClass().getName());
		fragmentTransaction.commit();
	}
	
	void setVideo() {
		String url = songObject.getPATCH_FULL();
		if (url != null) {
			if (songObject.getFormNet()) {
				new songDetailsServices().execute(songObject.getSONG_ID());
			}else{
				playVideo();
				if (TabAdapter == null) {
					TabAdapter = new OfflineTabPageAdapter(getSupportFragmentManager(), songObject);
					viewPager.setAdapter(TabAdapter);
					mIndicator.setViewPager(viewPager);
				}
			}
		} else {
			new songDetailsServices().execute(songObject.getSONG_ID());
		}
	}

	public void playVideo(){
		if (menuFragment!=null) {
			FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
			fragmentTransaction.remove(menuFragment).commit();
			bar.setVisibility(View.VISIBLE);
			mVideoView.setVisibility(View.VISIBLE);
		}
		isYoutubeAPI=false;
		
		
		String url = songObject.getPATCH_FULL();
		mVideoView.setOnToggleFullScreen(this);
		mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

			@Override
			public void onPrepared(MediaPlayer mp) {
				bar.setVisibility(View.GONE);
			}
		});

		calculateVideoViewSize();
		mVideoView.setMediaController(new VideoControllerStreamView(this));
		mVideoView.setDimensions(width, height);

		if (!BaseEngine.convertStringLongtoInteger(songObject.getTYPE_VIDEO()).equals(YOUTUBE)) {
			Uri uri = null;
			if (url.toLowerCase().contains("http".toLowerCase())) {
				uri = Uri.parse(checkVideoPath(url));
				isOnline = true;
			} else {
				uri = Uri.parse(url);
				isOnline = false;
			}
			mVideoView.setVideoURI(uri);
		} else {
			if (!isYoutubeAPI) {
				url=url.substring(url.length()-11, url.length());
				boolean videoHD = PreferenceUtils.getBoolean(VideoPlayActivity.this, TagName.KeyPreference_VideoHD,true);
				String lYouTubeFmtQuality = "17";
				if (videoHD) {
					lYouTubeFmtQuality = "18";
				}
	//			if(!videoHD){
	//				WifiManager lWifiManager = (WifiManager) VideoPlayActivity.this.getSystemService(Context.WIFI_SERVICE);
	//				TelephonyManager lTelephonyManager = (TelephonyManager) VideoPlayActivity.this.getSystemService(Context.TELEPHONY_SERVICE);
	//				if ((lWifiManager.isWifiEnabled() && lWifiManager.getConnectionInfo() != null && lWifiManager.getConnectionInfo().getIpAddress() != 0)
	//						|| ((lTelephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS || lTelephonyManager.getNetworkType() == 9 /* HSUPA */
	//								|| lTelephonyManager.getNetworkType() == 10 /* HSPA */
	//								|| lTelephonyManager.getNetworkType() == 8 /* HSDPA */
	//								|| lTelephonyManager.getNetworkType() == 5 /* EVDO_0 */
	//						|| lTelephonyManager.getNetworkType() == 6 /**/) && lTelephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED)) {
	//					lYouTubeFmtQuality = "18";
	//				}
	//			}
				mVideoView.setYoutubeId(lYouTubeFmtQuality, url);
			}else{
				menuFragment.YPlayer.cueVideo(songObject.getPATCH_FULL());
			}
		}
		if (!isYoutubeAPI) {
			mVideoView.requestFocus();
			mVideoView.start();
		}
	}
	public String checkVideoPath(String path) {
		return path.replaceAll(" ", "%20");
	}

	@Override
	protected void onPause() {
		super.onPause();
		mVideoView.suspend();
	}

	@Override
	protected void onResume() {
		super.onResume();
		mVideoView.resume();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		this.songObject=null;
		if(listSongs!=null){
			this.listSongs.clear();
			this.listSongs=null;
		}
				
	}
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (!isYoutubeAPI) {

			calculateVideoViewSize();
			// Checks the orientation of the screen
			if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
				getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
				getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
				// getActionBar().hide();
				mVideoView.setFullScreen(true);
			} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
				getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
				getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
				// getActionBar().show();
				mVideoView.setFullScreen(false);
			}
			mVideoView.setDimensions(width, height);
			mVideoView.getHolder().setFixedSize(width, height);
			bar.refreshDrawableState();
		}else{
			mVideoView.setDimensions(0, 0);
//			YoutubeFragment menuFragment
			if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
				menuFragment.YPlayer.setFullscreen(true);
			} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
				menuFragment.YPlayer.setFullscreen(false);
			}
		}
	}

	private void calculateVideoViewSize() {
		DisplayMetrics metrics = getResources().getDisplayMetrics();
		if (metrics.widthPixels < metrics.heightPixels) {
			height = (int) (metrics.widthPixels / 1.66);
			width = metrics.widthPixels;
		} else {
			width = metrics.widthPixels;
			height = metrics.heightPixels;
		}
		LinearLayout.LayoutParams layoutParams = (android.widget.LinearLayout.LayoutParams) relativeLayout.getLayoutParams();
		layoutParams.height = height;
		relativeLayout.setLayoutParams(layoutParams);
		relativeLayout.requestLayout();
	}

	@Override
	public void onToggleFullScreen(boolean isFullScreen) {
		setRequestedOrientation(isFullScreen ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	}

	public class OfflineTabPageAdapter extends FragmentStatePagerAdapter {
		SongObject songObject;

		public OfflineTabPageAdapter(FragmentManager fm, SongObject songObject) {
			super(fm);
			this.songObject = songObject;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			return null;
		}

		@Override
		public int getCount() {
			if (songObject.getFormNet())
				return 2;
			else
				return 1;
		}

		@Override
		public Fragment getItem(int i) {
			if (songObject.getFormNet())
				switch (i) {
				case 1:
					return CommentFragment.newInstance(songObject, TagName.Comment_typeVideo);
				default:
					if(listSongs!=null &&listSongs.size()>0){
						return VideoDetaisFragment.newInstance(listSongs, songObject);
					}else
						return VideoDetaisFragment.newInstance(songObject);
				}
			else
				return VideoDetaisFragment.newInstance( songObject);
		}
	}

	class songDetailsServices extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... params) {
			String str = WServiceLib.idDetais(CMD.CMD_SONG_DETAIL, params[0]);
//			BaseEngine.showLogformLongString(str);
			return str;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (result != null)
				try {
					JsonReader.readHeader(result);
						if(HomeData.headerObject.getCODE().equals("0")){
						ArrayList<SongObject> listsongs = JsonReader.readSongdetail(result);
						if (listsongs != null && listsongs.size() > 0) {
							songObject = listsongs.get(0);
//							songObject.showSonginfo();
							playVideo();
						}
						if (listSongs!=null && listSongs.size()>0) {
						}else
							listSongs = JsonReader.readListsong(result);
						if (TabAdapter == null) {
							TabAdapter = new OfflineTabPageAdapter(getSupportFragmentManager(), songObject);
							viewPager.setAdapter(TabAdapter);
							mIndicator.setViewPager(viewPager);
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
		}
	}
}